<template>
	<v-layout type="main">
		<div class="layout-top">
			<div class="rollback" @click="$router.push('/modelDevelop')">
				<img src="~@/assets/img/prev.png" alt="" />
				<span>返回</span>
			</div>

			<div class="code-description">
				<div class="dea_top">
					<div>
						<el-image
							class="nav_box"
							:src="detailData.avatar ? detailData.avatar : require('@/assets/img/drone3.jpg')"
							fit="fit"
						></el-image>
					</div>

					<div class="header_box">
						<div class="code-desc-header">
							<div class="title">
								<div class="title-header">
									<span>{{ detailData.name }}</span>
								</div>

								<div class="code-tags">
									<div class="user-tag tag">
										<img src="~@/assets/img/user.png" alt="" />
										{{
											detailData.create_user && (detailData.create_user.nick_name || detailData.create_user.username)
										}}
									</div>

									<div
										:class="[
											'status-tag tag',
											{
												danger: detailData.status === 'terminated',
												warning: detailData.status != 'terminated' && detailData.status != 'running',
												success: detailData.status === 'running',
											},
										]"
									>
										{{ statusMap[detailData.status] }}
									</div>

									<div class="time-tag tag">
										<span>创建时间：</span>
										{{ detailData.create_time }}
									</div>
								</div>

								<div class="staet_box">
									<plug-state :statusStr="detailData.status" />
								</div>
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="btns-container">
				<div class="alick-handle-btns">
					<el-button
						class="handle-btn"
						type="success"
						size="medium"
						@click="start"
						v-show="detailData.status == 'terminated'"
					>
						启动
					</el-button>

					<el-button
						class="handle-btn"
						type="success"
						size="medium"
						@click="run"
						v-show="detailData.status == 'running'"
					>
						运行
					</el-button>

					<!-- <el-button class="handle-btn" type="primary" size="medium" @click="goToLink"
            v-show="detailData.status != 'terminated'">
            打开仿真前端
          </el-button> -->

					<el-button
						class="handle-btn"
						type="primary"
						size="medium"
						@click="goToLink(detailData.simulation_home_url)"
						v-show="detailData.status != 'terminated' && !detailData.simulation_home_url_list"
					>
						打开仿真前端
					</el-button>

					<el-dropdown v-if="detailData.status == 'running' && detailData.simulation_home_url_list">
						<el-button type="primary" style="margin-right: 10px;">
							打开仿真前端<i class="el-icon-arrow-down el-icon--right"></i>
						</el-button>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item v-for="(item, index) in detailData.simulation_home_url_list" :key="index">
								<span @click="goToLink(item)"> 仿真前端{{ index + 1 }} </span>
							</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>

					<el-popover placement="bottom-end" width="80" trigger="hover" v-show="detailData.status == 'running'">
						<div class="alick-popover-handle-btns">
							<a class="handle-btn" href="javascript:;" @click="entry">进入VSCode</a>
							<a class="handle-btn" href="javascript:;" @click="entryBt">强化学习行为树</a>
						</div>
						<el-button class="handle-btn" type="warning" size="medium" slot="reference">模型开发</el-button>
					</el-popover>

					<el-button
						class="handle-btn"
						type="danger"
						size="medium"
						@click="stop"
						v-show="detailData.status != 'terminated'"
					>
						停止
					</el-button>

					<el-popover placement="bottom-end" width="80" trigger="hover">
						<div class="alick-popover-handle-btns">
							<a class="handle-btn" href="javascript:;" @click="exportModel">导出模型</a>
							<a class="handle-btn" href="javascript:;" @click="exportTask">训练任务</a>
							<a class="handle-btn" href="javascript:;" @click="exportAlgorithm">发布到公开算法</a>
						</div>
						<el-button class="handle-btn" type="warning" size="medium" slot="reference">更多</el-button>
					</el-popover>
				</div>
			</div>
		</div>

		<div class="tabs-left" v-if="thisRouter.length > 1">
			<el-tabs v-model="nowRouter" @tab-click="skip" v-show="!$route.meta.hideDetails">
				<el-tab-pane :label="e.meta.title" :name="e.name" v-for="(e, i) in thisRouter" :key="i" />
			</el-tabs>
		</div>

		<div :class="['layout-content', { 'layout-content-nodetail': $route.meta.hideDetails }]">
			<router-view class="content-detail" :detailData.sync="detailData" @infoData="infoData" v-if="detailData" />
		</div>

		<div v-if="showExportModelDialog">
			<plug-export-model
				:show_file.sync="showExportModelDialog"
				@infoShow="infoShowExport"
				:model_id="model_id"
				:biz_id="detailData.id"
				:business_type="3"
			/>
		</div>

		<!-- <el-dialog :visible.sync="showUpdateBaseDialog" title="模型开发基本信息" width="840px">
      <el-form class="form myself-form" ref="form" :rules="baseSubmitRules" :model="taskForm" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input type="text" v-model="taskForm.name" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input type="textarea" :rows="3" v-model="taskForm.desc" />
        </el-form-item>
        <el-form-item label="配图">
          <media-uploader accept=".jpg,.jpeg,.png,.JPG,.JPEG" :src="taskForm.avatar" @avatarPath="avatarPath" />
        </el-form-item>
        <el-form-item label="" prop="tensorboard">
          <el-checkbox v-model="taskForm.tensorboard">tensorboard</el-checkbox>
        </el-form-item>
        <el-form-item label=" ">
          <el-button class="none-type" type="primary" @click="commitBase">确定</el-button>
          <el-button class="none-type" @click="cancelBase">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog> -->
	</v-layout>
</template>

<script>
import plugState from "@/components/module/plug-state";
import { getMarketAlgorithmBySource } from "@/api/marketAlgorithm";
import { getGameTaskBySource } from "@/api/gameTask";
import {
	getGameExperimentDetail,
	putGameExperiment,
	startGameExperiment,
	stopGameExperiment,
	execCommandExperiment,
} from "@/api/gameExperiment";
import { domain } from "@/config";
import { getModelBySource } from "@/api/model";
import plugExportModel from "@/components/module/plug-export-model";
export default {
	data() {
		return {
			nowRouter: this.$route.name,
			thisRouter: [],
			detailData: null,
			taskForm: {},
			model_id: null,
			modelForm: { visibility: 0 },
			marketForm: {},
			taskSubmitRules: {
				task_id: [{ required: true, message: "该项为必填项" }],
			},
			// baseSubmitRules: {
			//   name: [
			//     { required: true, message: "该项为必填项" },
			//     { required: true, min: 1, max: 40, message: "长度在1到40个字符" },
			//   ],
			//   desc: [
			//     { required: true, message: "该项为必填项" },
			//     { required: true, min: 1, max: 200, message: "长度在1到40个字符" },
			//   ],
			// },
			modelSubmitRules: {
				model_id: [{ required: true, message: "该项为必填项" }],
			},
			marketSubmitRules: {
				model_id: [{ required: true, message: "该项为必填项" }],
			},
			showTaskDialog: false,
			showMarketDialog: false,
			// showUpdateBaseDialog: false,
			showExportModelDialog: false,
			taskOptions: [],
			modelOptions: [],
			marketAlgorithmOptions: [],
			task: null,
			model: null,
			algorithm: null,
			podUrl: null,
			simulationHomeUrl: null,
		};
	},
	components: {
		plugExportModel,
		plugState,
	},
	methods: {
		skip() {
			let path = `/modelDevelop/${this.thisRouter.filter((e) => e.name == this.nowRouter)[0].path}`;
			if (path == this.$route.path) return;
			this.$router.push({
				path,
				query: {
					id: this.$route.query.id,
				},
			});
		},

		async getDetail() {
			if (!this.$route.query.id) return;
			let res = await getGameExperimentDetail({ id: this.$route.query.id });
			if (res && res.data) {
				this.detailData = res.data;
				this.taskForm = JSON.parse(JSON.stringify(this.detailData));
				if (this.taskForm.simulation_home_url) {
					this.simulationHomeUrl = this.taskForm.simulation_home_url;
				}
			}
			this.genUrl();
		},
		avatarPath(data) {
			this.taskForm.avatar = data;
		},
		updateBase() {
			this.showUpdateBaseDialog = true;
		},

		commitBase() {
			this.$refs.form.validate(async (valid) => {
				if (valid) {
					let res = await putGameExperiment(this.taskForm);
					if (res && res.data) {
						this.getDetail();
						this.showUpdateBaseDialog = false;
					}
				}
			});
		},
		cancelBase() {
			this.showUpdateBaseDialog = false;
		},
		async exportTask() {
			if (!this.$route.query.id) return;
			let data = {
				source: this.detailData.id,
			};
			let task_id = null;
			let res = await getGameTaskBySource(data);
			if (res && res.data) {
				task_id = res.data.id;
			}
			let query = {
				experiment_id: this.detailData.id,
				task_id: task_id,
			};
			this.$router.push({
				path: "/gameTask/detail",
				query,
			});
		},
		async exportModel() {
			if (!this.$route.query.id) return;
			let data = {
				source: this.detailData.id,
			};
			let res = await getModelBySource(data);
			if (res && res.data) {
				this.model_id = res.data.id;
			}
			this.showExportModelDialog = true;
		},

		infoShowExport(data) {
			this.showExportModelDialog = data;
		},

		infoData(data) {
			console.log("infoData", data);
			this.getDetail();
			this.$forceUpdate();
		},
		async exportAlgorithm() {
			if (!this.$route.query.id) return;
			let data = {
				source: this.detailData.id,
			};
			let res = await getMarketAlgorithmBySource(data);
			let algorithm_id = null;
			console.log("res", res);
			if (res && res.data) {
				algorithm_id = res.data.id;
			}
			console.log("res2", res);
			let query = {
				experiment_id: this.detailData.id,
				algorithm_id: algorithm_id,
			};
			console.log("query", query);
			this.$router.push({
				path: "/algorithm/detail",
				query,
			});
		},
		update() {
			let query = {
				id: this.detailData.id,
			};
			this.$router.push({
				path: "/modelDevelop/detail",
				query,
			});
		},

		start() {
			startGameExperiment({ id: this.detailData.id });
		},
		async run() {
			await execCommandExperiment({
				...this.detailData,
				command: `cd /workspace/wiseRL/example/ && python main.py  --env_name  ${this.detailData.simulation_node_group?.image.name}`,
				game_id: this.detailData.id,
			});
			this.$message.success("运行成功");
		},
		async stop() {
			await stopGameExperiment({ id: this.detailData.id });
			this.getDetail();
			this.$forceUpdate();
		},
		entry() {
			let path = `${domain.split(":")[1]}:32658` + this.detailData.pod_url;
			// let path = "http://192.168.240.11:32658" + this.detailData.pod_url // 中船
			console.log("path", path);
			window.open(path, "_blank");
		},
		entryBt() {
			const { href } = this.$router.resolve({
				path: "/bTree", //路径
				query: {
					experiment_id: this.detailData.id,
				}, //传参
			});
			window.open(href);
		},
		goToLink(url) {
			console.log("url", url);
			window.open(url, "_blank");

			// // 增加自动化所仿真地址规则
			// if (this.simulationHomeUrl) {
			// 	window.open(this.simulationHomeUrl, "_blank");
			// 	return;
			// }
			// let path = this.podUrl;
			// if (this.podUrl == null) {
			// 	alert("仿真前端地址解析失败, 请在刷新页面后重试");
			// 	return;
			// }
			// window.open(path, "_blank");
		},
		goToTensorboard() {
			let path = `${domain.split(":")[1]}:8081` + this.detailData.tensorboard_url;
			console.log("path", path);
			window.open(path, "_blank");
		},
		genUrl() {
			if (this.detailData.status != "running" || !this.detailData.tcp_port_list) {
				return null;
			}
			try {
				let tcp_port_list = this.detailData.tcp_port_list;
				let simulationFrontUrl = process.env.VUE_APP_SIMULATION_URL;
				let port4000List = tcp_port_list.filter((map) => map.containerPort == "4000");
				let nodePort4000 = port4000List[0].nodePort;
				let frontPort = 4001;
				let port4001List = tcp_port_list.filter((map) => map.containerPort == "4001");
				let frontMap = port4001List[0].nodePort;
				let nodePort4009 = null;
				if (tcp_port_list.length > 9) {
					let port4009List = tcp_port_list.filter((map) => map.containerPort == "4009");
					if (port4009List.length) {
						nodePort4009 = port4009List[0].nodePort;
					}
				}
				let endpoint = tcp_port_list[0].endpoint.split(":")[0];
				if (nodePort4009 != null) {
					frontPort = 4009;
					frontMap = nodePort4009;
				}
				let url = `${simulationFrontUrl}/#/Menu?IP=${endpoint}&port1=${nodePort4000}&port2=${frontPort}&port3=${frontMap}`;
				this.podUrl = url;
			} catch (error) {
				console.error(error);
			}
		},
	},
	mounted() {
		let temp = this.$router.options.routes.filter((e) => e.name == "modelDevelop" && e.children);
		this.thisRouter = temp[0].children.filter((e) => !e.meta.hideDetails);
		this.getDetail();
		this.$EventBus.$on("experiment", (e) => {
			console.log(e);
			this.getDetail();
		});
	},
	destroyed() {
		this.$EventBus.$off("experiment");
	},
};
</script>
<style lang="less" scoped>
@import "~@/assets/css/detail-layout.less";

.code-description {
	// margin-bottom: 0;
}

.btns-container {
	// border: 1px solid #f00;

	.alick-handle-btns {
		// border: 1px solid #00f;
	}
}
</style>
